package com.sjb.sixteen_journey_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sjb.sixteen_journey_backend.common.CommonHandle;
import com.sjb.sixteen_journey_backend.common.ImagesProperties;
import com.sjb.sixteen_journey_backend.common.R;
import com.sjb.sixteen_journey_backend.entity.Comment;
import com.sjb.sixteen_journey_backend.entity.Follower;
import com.sjb.sixteen_journey_backend.entity.MyTime;
import com.sjb.sixteen_journey_backend.mapper.FollowerMapper;
import com.sjb.sixteen_journey_backend.mapper.MyTimeMapper;
import com.sjb.sixteen_journey_backend.service.ICommentService;
import com.sjb.sixteen_journey_backend.service.IMyTimeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sjb.sixteen_journey_backend.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 * <p>
 * 我的此刻表 服务实现类
 * </p>
 *
 * @author jcz
 * @since 2024-07-12
 */
@Service
@Slf4j
public class MyTimeServiceImpl extends ServiceImpl<MyTimeMapper, MyTime> implements IMyTimeService {

    @Autowired
    private MyTimeMapper myTimeMapper;


    @Autowired
    private CommonHandle commonHandle;

    @Autowired
    private ICommentService commentService;

    @Autowired
    private FollowerMapper followerMapper;
    @Autowired
    private ImagesProperties imagesProperties;
    @Override
//    public R addMyTime(MyTime myTime, ArrayList<MultipartFile> images) throws IOException {
    public R addMyTime(MyTime myTime) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        myTime.setUserId(id);
        //储存图片到本地
//        List<String> files = commonHandle.saveImages(images, imagesProperties.getMyTime());
//        myTime.setPath(files.toString());
        myTime.setPath(myTime.getImages().toString());

        boolean save = this.save(myTime);
        if (save) {
            return R.success(null, "添加我的时刻成功");
        } else {
            return R.error("添加我的时刻失败");
        }
    }

    @Override
    public R<MyTime> getMyTimeById(Integer myTimeId,Boolean f) {
        try {
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer userId = (Integer) map.get("id");
            MyTime myTime = myTimeMapper.selectMyTimeWithImages(myTimeId,userId);
            if (myTime != null) {
                if(f){
                    //每访问一下接口，其实浏览量就增加一次
                    UpdateWrapper<MyTime> wrapper = Wrappers.update();
                    wrapper.set("pv", myTime.getPv() + 1);
                    wrapper.eq("my_time_id", myTimeId);
                    myTimeMapper.update(null, wrapper);
                    myTime = myTimeMapper.selectMyTimeWithImages(myTimeId,userId);
                }

                //将字符串图片地址转换为数组
                List<String> strings = commonHandle.imageByStringToList(myTime.getPath());
                myTime.setImages(strings);

                //设置评论数量和当前用户对该用户是否关注
                myTime = this.setCountAndFollow(myTime);


                return R.success(myTime, "获取我的时刻成功");
            }
            return R.error("无“我的时刻”");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }



    @Override
    public R<List<MyTime>> getAllMyTime() {
        try {
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer userId = (Integer) map.get("id");
            List<MyTime> myTimes =myTimeMapper.getAllMyTime(userId);
            if (myTimes != null) {
                for (MyTime myTime : myTimes){
                    List<String> strings = commonHandle.imageByStringToList(myTime.getPath());
                    myTime.setImages(strings);
                    //设置评论数量和当前用户对该用户是否关注
                    myTime = this.setCountAndFollow(myTime);
                }
                return R.success(myTimes, "获取我的时刻成功");
            }
            return R.error("获取我的时刻失败");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public R<List<MyTime>> getAllMyTimeByUserId() {
        try {
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer userId = (Integer) map.get("id");
            List<MyTime> myTimes = myTimeMapper.getAllMyTimeByUserId(userId);
            if (myTimes != null) {
                for (MyTime myTime : myTimes){
                    List<String> strings = commonHandle.imageByStringToList(myTime.getPath());
                    myTime.setImages(strings);
                    //设置评论数量和当前用户对该用户是否关注
                    myTime = this.setCountAndFollow(myTime);
                }
                return R.success(myTimes, "获取到用户的我的时刻成功");
            }
            return R.error("获取我的时刻失败");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public R<List<MyTime>> getMyTimeByAnyUserId(Integer id) {
        try {
            List<MyTime> myTimes = myTimeMapper.getAllMyTimeByUserId(id);
            if (myTimes != null) {
                for (MyTime myTime : myTimes){
                    List<String> strings = commonHandle.imageByStringToList(myTime.getPath());
                    myTime.setImages(strings);
                    //设置评论数量和当前用户对该用户是否关注
                    myTime = this.setCountAndFollow(myTime);
                }
                return R.success(myTimes, "获取到用户的我的时刻成功");
            }
            return R.error("获取我的时刻失败");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public R deleteMyTimeById(Integer myTimeId) {
        try {
            MyTime myTime = this.getById(myTimeId);
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer userId = (Integer) map.get("id");
            if(userId.equals(myTime.getUserId())){
                if (this.removeById(myTimeId)) {
                    if(commonHandle.deleteAssociationTable(myTime.getPath(),myTime.getStatus(),myTimeId, imagesProperties.getMyTime())){
                        return R.success(null, "删除我的时刻成功");
                    }
                }
            }
            return R.error("删除我的此刻失败");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public R<List<MyTime>> getOtherMyTime(String site) {
        try {
            QueryWrapper<MyTime> wrapper = Wrappers.query();
            wrapper.like("experience", site).or().like("experience", site);
            List<MyTime> MyTimes = this.list(wrapper);
            List<MyTime> myTime1 = new ArrayList<>();
            for (MyTime myTime:MyTimes){
                R<MyTime> myTimeById = this.getMyTimeById(myTime.getMyTimeId(), false);
                myTime1.add(myTimeById.getData());
            }
            return R.success(myTime1, "获取相关时刻成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public MyTime setCountAndFollow(MyTime myTime) {
        Map<String, Object> map = ThreadLocalUtil.get();
        //我的此刻的评论数量
        QueryWrapper<Comment> query = Wrappers.query();
        query.eq("module_status",myTime.getStatus());
        query.eq("module_id", myTime.getMyTimeId());
        long count = commentService.count(query);
        myTime.setCommentCount(count);

        Follower follower = new Follower();
        if(map!=null){
            Integer userId = (Integer) map.get("id");
            //当前用户对该用户是否关注
            QueryWrapper<Follower> followerQueryWrapper = Wrappers.query();
            followerQueryWrapper.eq("user_id",userId);
            followerQueryWrapper.eq("fans_id", myTime.getUserId());
            follower = followerMapper.selectOne(followerQueryWrapper);
        }
        myTime.setIs_followedByUser(follower==null ? false :follower.getStatus());
        return myTime;
    }
}
